<template>
  <div class="category-management">
    <!-- 头部操作区 -->
    <div class="header">
      <el-button type="primary" @click="openDialog(1)">
        <el-icon><Plus /></el-icon>新增菜品分类
      </el-button>
      <el-button type="success" @click="openDialog(2)">
        <el-icon><Plus /></el-icon>新增套餐分类
      </el-button>
    </div>

    <!-- 分类表格 -->
    <el-table :data="categoryList" v-loading="loading" border stripe style="width: 100%">
      <el-table-column prop="name" label="分类名称" width="300" align="center"/>
      <el-table-column prop="type" label="分类类型" width="200" align="center">
        <template #default="{ row }">
          <el-tag :type="row.type === 1 ? 'primary' : 'success'">
            {{ row.type === 1 ? '菜品分类' : '套餐分类' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="sort" label="排序" width="200" align="center"/>
      <el-table-column prop="updateTime" label="最后操作时间" width="200" align="center" />
      <el-table-column label="操作" width="250" align="center">
        <template #default="{ row }">
          <el-button size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <Pagination
        :currentPage="currentPage"
        :pageSize="pageSize"
        :total="total"
        @update:currentPage="handlePageChange"
        @update:pageSize="handlePageSizeChange"
    />

    <!-- 新增/编辑分类对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="30%"
        @closed="resetForm"
    >
      <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="100px"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="分类类型" prop="type">
          <el-tag :type="form.type === 1 ? 'primary' : 'success'">
            {{ form.type === 1 ? '菜品分类' : '套餐分类' }}
          </el-tag>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number
              v-model="form.sort"
              :min="1"
              :max="999"
              controls-position="right"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import Pagination from "@/components/common/Pagination.vue";
import {addCategory, deleteCategory, pageCategoryList, updateCategory} from "@/api/category";

// 数据状态
const loading = ref(false) // 加载状态
const categoryList = ref([])
//对话框状态
const dialogVisible = ref(false)
const dialogTitle = ref('')

const formRef = ref(null)
const isEdit = ref(false)

//分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 表单数据
const form = ref({
  id: null,
  name: '',
  type: 1, // 1-菜品分类 2-套餐分类
  sort: 1
})

// 打开对话框（修改type 1/2）
const openDialog = (type) => {
  dialogTitle.value = type === 1 ? '新增菜品分类' : '新增套餐分类'
  form.value.type = type
  dialogVisible.value = true
  isEdit.value = false
}

// 验证规则
const rules = {
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 2, max: 30, message: '长度在2到30个字符', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '请输入排序值', trigger: 'blur' }
  ]
}

// 初始化加载数据
const loadCategoryList = async () => {
  if (loading.value) return;

  loading.value = true
  try {
    const params = {
      pageNo: currentPage.value,
      pageSize: pageSize.value
    }
    const res = await pageCategoryList(params);
    await new Promise(resolve => setTimeout(resolve, 200)) // 模拟延迟
    if (res.code === '200') {
      categoryList.value = res.data.records
      total.value = res.data.total
    }else{
      ElMessage.error(res.msg || '获取分类列表失败')
    }
  } catch (error) {
    ElMessage.error('获取分类列表失败')
  } finally{
    loading.value = false
  }
}

// 编辑分类
const handleEdit = (row) => {
  dialogTitle.value = `编辑${row.type === 1 ? '菜品' : '套餐'}分类`
  form.value = { ...row } //拷贝数据
  dialogVisible.value = true
  isEdit.value = true
}

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate()
    if (isEdit.value) {
      const submitForm = {
        id: form.value.id,
        name: form.value.name,
        sort: form.value.sort
      }

      // 编辑
      const res = await updateCategory(submitForm);
      if (res.code === '200') {
        ElMessage.success(res.data || '修改成功')
        await loadCategoryList()
      }else{
        ElMessage.error(res.msg || '修改分类失败')
      }
    } else {
      const submitForm = {
        name: form.value.name,
        type: form.value.type,
        sort: form.value.sort
      }
      // 新增api
      const res = await addCategory(submitForm)
      if (res.code === '200') {
        ElMessage.success(res.data||'添加成功');
        await loadCategoryList()
      }else{
        ElMessage.error(res.msg || '添加分类失败')
      }
    }
    dialogVisible.value = false
  } catch (error) {
    ElMessage.error('表单验证未通过')
  }
}

// 删除分类
const handleDelete = (id) => {
  ElMessageBox.confirm('确定要删除该分类吗?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const res = await deleteCategory(id)
    if (res.code === '200') {
      ElMessage.success(res.data||'删除成功')
      await loadCategoryList()
    }else{
      ElMessage.error(res.msg||'删除失败')
    }
  }).catch(() => {})//取消删除
}

// 重置表单
const resetForm = () => {
  formRef.value?.resetFields()
  form.value = {
    id: null,
    name: '',
    type: 1,
    sort: 1
  }
}

// 分页处理函数
const handlePageChange = (newPage) => {
  currentPage.value = newPage;
  loadCategoryList();
};

const handlePageSizeChange = (newSize) => {
  pageSize.value = newSize;
  currentPage.value = 1; // 必须重置页码
  loadCategoryList();
};

// 初始化加载
onMounted(() => {
  loadCategoryList()
})
</script>

<style scoped>
.category-management {
  padding: 20px;
}

.header {
  margin-bottom: 20px;
}
</style>